﻿using System;
using System.Collections.Generic;
using System.Text;
using ZX.SYS.Library;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.IO;
using ZX.Common;
using ZX.SYS.Library;
using System.Data;
using ZX.DAL.DBExtend;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Xml;
namespace ZX.SYS.Bussiness
{
    public class MQproccess : BLL.Extend.BaseBussnies
    {
        public static readonly string serverURL = MQOut.AllURL;
        public DataTable getMessageList(string userid, string status)
        {
            DbSql dq = new DbSql();
            string condition = "";
            if (userid != "" || userid != string.Empty)
            {
                condition = " and AddUser='" + userid + "'";
            }
            if (status != "")
                condition += " and mstatus=" + status;
            return dq.ExecuteQuery(@"SELECT [mbid]
                                      ,[content]
                                      ,[Mphone]
                                      ,[sendtime]
                                      ,[mstatus]
                                  FROM [MQMessage] where 1=1 " + condition);
        }


        //插入获取的短信
        public bool RecMessage(string cont,string phone,string time)
        {
            MQReback mqr = new Library.MQReback();
                mqr.mrid = Guid.NewGuid();
                mqr.neirong = cont;
                mqr.ShouJi = phone;
                mqr.kuozhanhao = "";
                mqr.JieShouShi = Convert.ToDateTime(time);
                BaseBussnies bmqr = new BaseBussnies(mqr);
                return  bmqr.Insert();
        }
       
        /// <summary>
        /// 将未发生短信的发送
        /// </summary>
        public void AutoSendExe()
        {
            DbSql dq = new DbSql();
            DataTable dt = getMessageList("", "0");
            string sql = "";
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                if (sendmessage(dt.Rows[i]["Mphone"].ToString(), dt.Rows[i]["content"].ToString()) == "0")
                {
                    sql = "update MQmessage set mstatus=1 where mbid='" + dt.Rows[i]["mbid"].ToString() + "'";
                    dq.ExecuteSql(sql);
                }
            }
        }

        /// <summary>
        /// 获取回复的短信，将其保存到数据库中
        /// </summary>
        public void AutoRecdExe()
        {
            return;
            DataTable dta = (new MQOut()).Account();
            for (int j = 0; j< dta.Rows.Count; j++)
            {
                DataTable dt = GetByXml(serverURL.Replace("send", "getmsg") + "?username=" + dta.Rows[j]["Acount"].ToString().Split(';')[0] + "&password=" + dta.Rows[j]["Apwd"].ToString());
                if (dt.Rows.Count > 0)
                {
                    MQReback mqr = new Library.MQReback();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        mqr.mrid = Guid.NewGuid();
                        mqr.neirong = dt.Rows[i]["Msg"].ToString();
                        mqr.ShouJi = dt.Rows[i]["Mobile"].ToString();
                        mqr.kuozhanhao = dt.Rows[i]["SendCode"].ToString();
                        mqr.JieShouShi = Convert.ToDateTime(dt.Rows[i]["MDate"].ToString());
                        BaseBussnies bmqr = new BaseBussnies(mqr);
                        bmqr.Insert();
                    }

                }
            }
        }

        
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone">手机号码</param>
        /// <param name="msg">短信内容</param>
        /// <returns></returns>
        public string sendmessage(string phone, string msg)
        {
            //return (new MQOut()).sendmessage(phone, msg);
            return (new MQOut()).CheckSms(phone, msg);
        }


        //将发送的短信插入数据库
        public void insert(string mes, DateTime sendtime, string phone, int havesend,Guid userid)
        {
            BaseBussnies bmmb = new BaseBussnies(SetValue(mes,sendtime,phone,havesend,userid));
            bmmb.Insert();
        }

        //赋值
        public MQMessage SetValue(string mes, DateTime sendtime, string phone, int havesend, Guid userid)
        {
            MQMessage mmb = new MQMessage();
            mmb.mbid = Guid.NewGuid();
            mmb.Mphone = phone;
            mmb.AddUser = userid;
            mmb.AddTime = DateTime.Now;
            mmb.content = mes;
            mmb.mstatus = havesend;
            mmb.sendtime = sendtime;
            mmb.mtype = 0;//0为短信
            return mmb;
        }
        /// <summary>
        /// 根据用户获取群组类型
        /// </summary>
        /// <param name="ClassId">ID</param>
        /// <returns></returns>
        public IList<MQOrgType> GetMQOrgType(string userid)
        {
            this.entity = new MQOrgType();
            return GetEntitys<MQOrgType>("AddUser='" + userid + "'");
        }

        #region

        //更新回复短信的状态
        public int UpdateReback(string bid,string mes, DateTime sendtime, string phone, int havesend, Guid userid)
        {
            MQMessage mqm = SetValue(mes, sendtime, phone, havesend, userid);
            BaseBussnies bmqm = new BaseBussnies(mqm);
            bmqm.Insert();

            DbSql dq = new DbSql();
            string sql = "update MQReback set IsDafu='是',DafuID='" + mqm.mbid + "' where mrid='" + bid + "'";
            return dq.ExecuteSql(sql);
        }

        /// <summary>
        /// 导入用户，构成群组成员
        /// </summary>
        /// <param name="type">导入来源：0组织架构(V_UserMessage)，1客户(V_CrmCustomerShowM)</param>
        /// <param name="users">USERID字符串</param>
        /// <returns>插入结果：1，成功，0，失败</returns>
        public string InsertUser(string type,string users,string userid,string orgtypeid)
        {
            string sql = "";
            string back = "1";
            DbSql dq = new DbSql();
            if (type == "V_CrmCustomerShowM")
            {
                sql = @"SELECT NEWID() as obid
	                      ,SUBSTRING ([Decisionmaker],1 ,1) as xing
                          ,SUBSTRING ([Decisionmaker],2,3) as Ming
                          ,'' as NiCheng
                          ,GETDATE() as ShengRi
                          ,[DecisionTel] as ShouJi
                          ,'' as email
                          , 0 as qq
                          ,'' as msn
                          ,'' as weibo
                          ,'' as AiHao
                          ,[CustomerName] as GongSi
                          ,[DecisionPosition] as ZhiYe
                          ,[DetailAddress] as TongXinDiZhi
                          ,'' as YouBian
                          ,'" + userid + "' as AddUser"
                             + ",GETDATE() as [AddTime] FROM [V_CrmCustomerShowM] "
                             + " where Mobile in ('" + users.Replace(",","','")+ "')";
                DataTable dt = dq.ExecuteQuery(sql);
                Library.MQOrgBody mqb = new Library.MQOrgBody();
                Library.MQOTB mqt = new Library.MQOTB();
                try
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        mqb.obid = new Guid(dt.Rows[i]["obid"].ToString());
                        mqb.Xing = dt.Rows[i]["xing"].ToString();
                        mqb.Ming = dt.Rows[i]["Ming"].ToString();
                        mqb.ShouJi = dt.Rows[i]["ShouJi"].ToString();
                        mqb.ZhiYe = dt.Rows[i]["ZhiYe"].ToString();
                        mqb.TongXinDiZhi = dt.Rows[i]["TongXinDiZhi"].ToString();
                        mqb.GongSi = dt.Rows[i]["GongSi"].ToString();
                        mqb.AddUser = new Guid(dt.Rows[i]["AddUser"].ToString());
                        mqb.AddTime = DateTime.Now;
                        BaseBussnies bmqb = new BaseBussnies(mqb);
                        bmqb.Insert();

                        mqt.otbid = Guid.NewGuid();
                        mqt.obid = new Guid(dt.Rows[i]["obid"].ToString());
                        mqt.otid = new Guid(orgtypeid);
                        BaseBussnies bmqt = new BaseBussnies(mqt);
                        bmqt.Insert();
                    }
                }
                catch (Exception ex) { back = ex.ToString(); }
               //dq.DtBulkWrite(dt, "MQOrgBody");
            }
            else
            {
                sql = @"SELECT NEWID() as obid
	                      ,SUBSTRING ([Name],1 ,1) as xing
                          ,SUBSTRING ([Name],2,3) as Ming
                          ,'' as NiCheng
                          ,GETDATE() as ShengRi
                          ,[mphone] as ShouJi
                          ,[Email] as email
                          , 0 as qq
                          ,'' as msn
                          ,'' as weibo
                          ,'' as AiHao
                          ,'中旭-'+[DeptName] as GongSi
                          ,'' as ZhiYe
                          ,'' as TongXinDiZhi
                          ,'' as YouBian
                          ,'" + userid + "' as AddUser"
                         +" ,GETDATE() as [AddTime]"
                      +"FROM [V_UserMessage]"
                      + "where [UserID]  in ('" + users.Replace(",", "','") + "')";

                DataTable dt = dq.ExecuteQuery(sql);
                Library.MQOrgBody mqb = new Library.MQOrgBody();
                Library.MQOTB mqt = new Library.MQOTB();
                try
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        mqb.obid = new Guid(dt.Rows[i]["obid"].ToString());
                        mqb.Xing = dt.Rows[i]["xing"].ToString();
                        mqb.Ming = dt.Rows[i]["Ming"].ToString();
                        mqb.ShouJi = dt.Rows[i]["ShouJi"].ToString();
                        mqb.email = dt.Rows[i]["email"].ToString();
                        mqb.GongSi = dt.Rows[i]["GongSi"].ToString();
                        mqb.AddUser = new Guid(dt.Rows[i]["AddUser"].ToString());
                        mqb.AddTime = DateTime.Now;
                        BaseBussnies bmqb = new BaseBussnies(mqb);
                        bmqb.Insert();


                        mqt.otbid = Guid.NewGuid();
                        mqt.obid = new Guid(dt.Rows[i]["obid"].ToString());
                        mqt.otid = new Guid(orgtypeid);
                        BaseBussnies bmqt = new BaseBussnies(mqt);
                        bmqt.Insert();
                    }
                }
                catch (Exception ex) { back = ex.ToString(); }
                //dq.DtBulkWrite(dt, "MQOrgBody");
            }
            return back;
        
        }
        #endregion
  

        /// <summary>
        /// 根据XML字符串返回datatable
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public DataTable GetByXml(string xmlpath)
        {
            DataSet ds = new DataSet();
            try
            {
                ds.ReadXml(xmlpath);
            }
            catch (Exception)
            {
                return new DataTable();
            }
            return ds.Tables[0];
        }

        public DataTable GetUserType(string typeid)
        {
            string sql = @"SELECT [otbid]
                          ,[MQOTB].[obid]
                          ,[otid]
                          ,[Xing]
                          ,[Ming]
                          ,[Nicheng]
                          ,[ShouJi]
                          ,[GongSi]
                          ,[email]
                          ,[ZhiYe]
                          ,[ShengRi]
                      FROM [MQOTB] left join MQOrgBody on [MQOTB].obid=MQOrgBody.obid where otid='" + typeid+"'";

            return (new DbSql()).ExecuteQuery(sql);
        }

        //返回所要群组名称
        public DataTable GetGroupType()
        {
            string sql = @"SELECT  [otid]
                          ,[otname]
                          ,[adduser]
                      FROM [MQOrgType]";
            return (new DbSql()).ExecuteQuery(sql);
        }

        public string InserGroupType(string obids,string tid)
        {
            MQOTB otb = new Library.MQOTB();
            string[] bids = obids.Split(';');
            try
            {
                for (int i = 0; i < bids.Length; i++)
                {
                    otb.otbid = Guid.NewGuid();
                    otb.otid = new Guid(tid);
                    otb.obid = new Guid(bids[i]);
                    BaseBussnies botb = new BaseBussnies(otb);
                    botb.Insert();
                }

                return "归类成功！";
            }
            catch (Exception) { return "归类过程中出现异常，请检查！"; }
        }

        public int DeleteFromType(string ibs,string tid)
        {
            string nibs = "'" + ibs.Replace(";","','") + "'";
            string sql = @"delete from  MQOTB where otid='" + tid + "' and obid in(" + nibs + ")";
            return (new DbSql()).ExecuteSql(sql);
        }
    }
}
